using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Web;
using System.Net;

namespace Rapier.Kodachi
{
    public partial class ErrorWindow : Form
    {
        private Exception exception;

        public ErrorWindow(Exception exception)
        {
            InitializeComponent();
            this.exception = exception;
        }

        private void bSend_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            SendToBugzScout();
            MessageBox.Show("Thank you for helping us to improve Kodachi!", "Thank You", MessageBoxButtons.OK, MessageBoxIcon.None);
            Close();
        }

        private void bCancel_Click(object sender, EventArgs e)
        {
            Close();
        }


        private void SendToBugzScout()
        {
            /*
             * Valid parameters:
             *      email
             *      description
             *      extra
             *      scoutUserName
             *      scoutProject
             *      scoutArea
             *      defaultMessage ? (message to send back to user automatically...we'll just set this in FogBugz instead)
             */
            StackTrace stackTrace = new StackTrace(exception);
            StackFrame stackFrame = stackTrace.GetFrame(0);
            string description = System.Windows.Forms.Application.ProductVersion + ":" + exception.TargetSite.ReflectedType.FullName + ":" + stackFrame.GetILOffset();
            string extraInfo = "OS: " + Environment.OSVersion.VersionString + Environment.NewLine;
            extraInfo += exception.StackTrace + Environment.NewLine;
            
            //Inner exception if we have one...
            if (exception.InnerException != null)
            {
                extraInfo += Environment.NewLine + "Inner Exception: " + exception.InnerException.Message;
                extraInfo += Environment.NewLine + exception.InnerException.StackTrace + Environment.NewLine;
            }

            if (tbExtraInfo.Text != String.Empty)
            {
                extraInfo += Environment.NewLine + "Extra Info:" + Environment.NewLine + tbExtraInfo.Text;
            }
            string parameters = String.Format("description={0}&extra={1}&scoutUserName=Administrator&scoutProject=Kodachi&scoutArea=Code", HttpUtility.UrlEncode(description), HttpUtility.UrlEncode(extraInfo));
            if (tbEmail.Text != String.Empty)
            {
                parameters += "&email=" + tbEmail.Text;
            }

            string response = Global.HttpPost("http://rapiersoftware.com/fogbugz/scoutSubmit.asp", parameters);
        }
    }
}